<template>
    <div class="main">
        <div class="search">
            <label>管理员搜索：</label>
            <el-input v-model="ad.username" style="width: 240px" placeholder="请输入姓名" clearable>
            </el-input>
            <el-button type="primary" @click="search" style="margin-left: 10px;">查询</el-button>
            <el-button type="primary" style="margin-left: 10px;" @click="resetSearch">重置</el-button>
            <el-button class="button" :icon="Plus" @click="add">添加</el-button>
            <el-button class="button" :icon="Delete" @click="deleteRows">批量删除</el-button>
        </div>
        <div class="data">
            <div class="gird">
                <el-table :data="tableData" border style="width: 100%" :header-cell-style="{ textAlign: 'center' }"
                    :cell-style="{ textAlign: 'center' }" ref="tableRef">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="id" label="编号" width="80" />
                    <el-table-column label="头像" fixed width="100">
                        <template #default="scope">
                            <div :style="'background-image: url(' + (baseUrl + scope.row.avatar_url) + ')'"></div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="username" label="姓名" width="140" />
                    <el-table-column prop="enabled" label="是否启用" width="120">
                        <template #default="scope">
                            <el-switch @change="updateEnabled123(scope.row)" v-model="scope.row.enabled" />
                        </template>
                    </el-table-column>
                  <el-table-column prop="status" label="状态" width="120">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
                        {{ scope.row.status === 0 ? '正常' : '异常' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="locked" label="锁定" width="120">
                    <template #default="scope">
                      <el-switch @change="updateLocked123(scope.row)" v-model="scope.row.locked" />
                    </template>
                  </el-table-column>
                    <el-table-column prop="createdTime" label="创建时间" width="240" />
                    <el-table-column prop="updatedTime" label="上次更新" width="240" />
                    <el-table-column prop="createdBy" label="创建者" width="240" />
                    <el-table-column prop="createdBy" label="修改者" width="240" />
                    <el-table-column fixed="right" label="操作" min-width="280">
                        <template #default="scope">
                            <el-button type="primary" :icon="Edit" @click="editRow(scope.row)"
                                size="small">编辑</el-button>
                            <el-button type="success" @click="assignGroup(scope.row)" size="small">分配用户组</el-button>
                            <el-button type="danger" :icon="Delete" @click="deleteRow(scope.row)" size="small">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="pagination" style="margin-top: 10px;">
                <el-pagination v-model:current-page="pi.pageNo" v-model:page-size="pi.pageSize"
                    :page-sizes="[5, 10, 15, 30, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pi.total" background @change="paginate" />
            </div>
        </div>
      <el-dialog
          v-model="show"
          :title="title"
          width="500px"
          draggable
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :destroy-on-close="true"
      >
        <!-- 管理员信息表单 -->
        <el-form :model="afm" ref="sfRef" label-width="80px" label-position="left">
          <el-row>
            <el-col :span="16">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="afm.username" placeholder="请输入用户名" clearable></el-input>
              </el-form-item>

              <!-- 新增管理员时的密码设置 -->
              <el-form-item label="密码" prop="password" v-if="!afm.id">
                <el-input v-model="afm.password" placeholder="请输入密码" show-password></el-input>
              </el-form-item>

              <!-- 编辑管理员时的密码修改 -->
              <template v-if="afm.id">
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input v-model="afm.oldPassword" placeholder="请输入当前密码" show-password></el-input>
                </el-form-item>

                <el-form-item label="新密码" prop="newPassword" v-if="afm.oldPassword">
                  <el-input v-model="afm.newPassword" placeholder="请输入新密码" show-password></el-input>
                </el-form-item>

                <el-form-item label="确认密码" prop="confirmPassword" v-if="afm.newPassword">
                  <el-input v-model="afm.confirmPassword" placeholder="请再次输入新密码" show-password></el-input>
                </el-form-item>
              </template>

              <el-form-item label="是否启用" prop="enabled">
                <el-switch
                    v-model="afm.enabled"
                    active-text="启用"
                    inactive-text="禁用"
                    :active-value="true"
                    :inactive-value="false"
                />
              </el-form-item>

              <el-form-item label="状态" prop="status">
                <el-select v-model="afm.status" placeholder="请选择状态" style="width: 100%">
                  <el-option label="正常" :value="0" />
                  <el-option label="异常" :value="1" />
                </el-select>
              </el-form-item>

              <el-form-item label="是否锁定" prop="locked">
                <el-switch
                    v-model="afm.locked"
                    active-text="锁定"
                    inactive-text="正常"
                    :active-value="true"
                    :inactive-value="false"
                    :disabled="!afm.id"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="头像" prop="avatar_url">
                <el-upload
                    class="avatar-uploader"
                    action="/api/admin/upload/avatar"
                    :on-success="uploadSuccess"
                    :show-file-list="false"
                    :headers="headers"
                    :auto-upload="true"
                >
                  <div class="img" v-if="afm.avatar_url" :style="'background-image: url(' + (afm.avatar_url) + ')'"></div>
                  <el-icon v-else class="icon"><Plus /></el-icon>
                </el-upload>
                <div class="avatar-tip">点击上传头像</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="show = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确认</el-button>
          </div>
        </template>
      </el-dialog>

        <!-- 分配用户组对话框 -->
        <el-dialog v-model="showAssignDialog" title="分配用户组" width="500px" draggable :close-on-click-modal="false">
            <el-form :model="assignForm" label-width="100px">
                <el-form-item label="用户组">
                    <el-select v-model="assignForm.userGroupId" placeholder="请选择用户组" style="width: 100%">
                        <el-option v-for="group in userGroups" :key="group.id" :label="group.name" :value="group.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showAssignDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirmAssign">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { Plus, Edit, Search, Refresh, Delete, CircleClose, CircleCheck } from '@element-plus/icons-vue'
import { ref, onMounted, toRaw, nextTick } from 'vue';
import {
    findAll, deleteById, save, updateAdmin, updateEnabled as updateUserEnabled,
    findById, updateRole as updateRoleAdmin, deleteAll,updateLocked,findUserGroup, saveUserGroup,
  updateUserGroup
} from "@/api/AdminApi"
import { ElMessageBox, ElMessage } from 'element-plus'
onMounted(() => {
    search();
})

const tableData = ref();
async function search() {
    let params = ad.value;
    let resp = await findAll(pi.value.pageNo, pi.value.pageSize, params);
    console.log(pi.value.pageNo, pi.value.pageSize)
    tableData.value = resp.records;
    console.log(resp.data)
    pi.value.pageNo = resp.current;
    pi.value.total = resp.total;
    pi.value.pageSize = resp.size;
    tableData.value = tableData.value.map(item => {
        // 将 status 字段从 0/1 转换为 false/true
        return {
            ...item,
            enabled: item.enabled === true,
            locked: item.locked === 1,
        };
    });
    console.log(tableData.value)
}

//分页信息
const pi = ref({
    pageNo: 1,
    pageSize: 5,
    total: 0,
});

//分页查询
function paginate() {
    search();
}

const ad = ref({
    username: "",
});
function resetSearch() {
    ad.value = {
        name: "",
    };
    search();
}
//点击行数后单选框被勾选
let tableRef;
//批量删除
function deleteRows() {
    let rows = tableRef.getSelectionRows();
    let ids = [];
    for (let row of rows) {
        ids.push(toRaw(row).id);
    }
    deleteAllRows(ids);
}
async function deleteAllRows(ids) {
    if (ids.length == 0) {
        ElMessage({
            message: "请选择想要删除的行",
            type: "warning",
        });
    } else {
        ElMessageBox.confirm("是否确认删除所选行?", "Warning", {
            type: "warning",
        })
            .then(async () => {
                //向后台发送ajax请求
                let resp = await deleteAll(ids);
                if (resp.code === '200') {
                    ElMessage({
                        message: resp.msg,
                        type: "success",
                    });
                    search();
                } else {
                    ElMessage({
                        message: resp.msg,
                        type: "warning",
                    });
                }
            })
            .catch(() => { });
    }
}
async function updateEnabled123(row) {
    // console.log(admin);
    if (row.enabled === false) {
        let resp = await updateUserEnabled(row.id, false);
        if (resp.code === '200') {
            ElMessage({
                message: "禁用成功",
                type: "success",
            });
        }
        else {
            ElMessage({
                message: resp.msg,
                type: "error",
            });
        }
    }
    else {
        let resp = await updateUserEnabled(row.id, true);
        if (resp.code === '200') {
            ElMessage({
                message: "启用成功",
                type: "success",
            });
        }
        else {
            ElMessage({
                message: resp.msg,
                type: "error",
            });
        }
    }
}
async function updateLocked123(row) {
  console.log(row);
  if (row.locked === false) {
    let resp = await updateLocked(row.id, 0);
    if (resp.code === '200') {
      ElMessage({
        message: "锁定成功",
        type: "success",
      });
    }
    else {
      ElMessage({
        message: resp.msg,
        type: "error",
      });
    }
  }
  else {
    let resp = await updateLocked(row.id, 1);
    if (resp.code === '200') {
      ElMessage({
        message: "解锁成功",
        type: "success",
      });
    }
    else {
      ElMessage({
        message: resp.msg,
        type: "error",
      });
    }
  }
}
async function updateRole(row) {
    console.log(row.role);
    // console.log(row.id);
    await updateRoleAdmin(row.id, row.role);
    ElMessage({
        message: "权限修改成功",
        type: "success",
    });
}

function deleteRow(row) {
    let id = row.id;
    deleteAdmin(id)
}

//删除函数
function deleteAdmin(id) {
    ElMessageBox.confirm("是否确认删除所选行?", "警告！", {
        type: "warning",
    })
        .then(async () => {
            let resp = await deleteById(id);
            if (resp.code === '200') {
                console.log("111")
                ElMessage({
                    message: resp.msg,
                    type: "success",
                });
                search();
            } else {
                ElMessage({
                    message: resp.msg,
                    type: "error",
                });
            }
        })
        .catch(() => { });
}
const show = ref(false);

// 更新 afm 的初始值以包含密码相关字段
const afm = ref({
  id: undefined,
  username: "",
  password: "",        // 新增管理员时使用
  oldPassword: "",     // 修改密码时的旧密码
  newPassword: "",     // 修改密码时的新密码
  confirmPassword: "", // 修改密码时的确认密码
  enabled: true,
  status: 0,
  locked: 0,
  avatar_url: "",
})
const title = ref("新增管理员");
// 更新 add 函数
function add() {
  show.value = true;
  title.value = "新增管理员";
  afm.value = {
    id: undefined,
    username: "",
    password: "",
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
    enabled: true,
    status: 0,
    locked: 0,
    avatar_url: "",
  };
}
// 更新 submitForm 函数以处理密码验证
function submitForm() {
  let adm = toRaw(afm.value);

  // 如果是编辑模式且输入了旧密码，需要进行密码验证
  if (adm.id && adm.oldPassword) {
    // 检查是否输入了新密码
    if (!adm.newPassword) {
      ElMessage({
        message: "请输入新密码",
        type: "error",
      });
      return;
    }

    // 检查新密码和确认密码是否一致
    if (adm.newPassword !== adm.confirmPassword) {
      ElMessage({
        message: "两次输入的密码不一致",
        type: "error",
      });
      return;
    }

    // 检查新密码是否与旧密码相同
    if (adm.oldPassword === adm.newPassword) {
      ElMessage({
        message: "新密码不能与旧密码相同",
        type: "error",
      });
      return;
    }
  }

  // 根据是否有 ID 判断是更新还是新增
  if (adm.id) {
    update(adm);
  } else {
    saveUser(adm);
  }
}
// 更新 saveUser 函数以处理密码字段
async function saveUser(adm) {
  // 构造提交数据，移除不需要的字段
  const submitData = {
    username: adm.username,
    password: adm.password,
    enabled: adm.enabled,
    status: adm.status,
    locked: adm.locked?1:0,
    avatar_url: adm.avatar_url,
  };

  let resp = await save(submitData);
  if (resp.code === '200') {
    ElMessage({
      message: resp.msg,
      type: "success",
    });
    search();
    show.value = false;
  } else {
    ElMessage({
      message: resp.msg,
      type: "error",
    });
  }
}

// 更新 editRow 函数
function editRow(row) {
  show.value = true;
  title.value = "修改管理员";

  // 深拷贝行数据以避免直接修改表格数据
  afm.value = {
    id: row.id,
    username: row.username,
    password: "",        // 新增管理员时使用
    oldPassword: "",     // 修改密码时的旧密码
    newPassword: "",     // 修改密码时的新密码
    confirmPassword: "", // 修改密码时的确认密码
    enabled: row.enabled,
    status: row.status,
    locked: row.locked,
    avatar_url: row.avatar_url,
  };
}

// 更新 update 函数以处理密码修改
async function update(adm) {
  // 构造提交数据
  const submitData = {
    id: adm.id,
    username: adm.username,
    enabled: adm.enabled,
    status: adm.status,
    locked: adm.locked ? 1 : 0,
    avatar_url: adm.avatar_url,
  };

  // 如果有旧密码，则添加密码修改相关字段到提交数据中
  if (adm.oldPassword) {
    submitData.password = adm.newPassword;
  }

  let resp = await updateAdmin(submitData);
  if (resp.code === '200') {
    ElMessage({
      message: resp.msg,
      type: 'success',
    });
    search();
    show.value = false;
  } else {
    ElMessage({
      message: resp.msg,
      type: 'error',
    });
  }
}

const showAssignDialog = ref(false);
const assignForm = ref({
  adminId: '',
  userGroupId: ''
});
const userGroups = ref([]); // 存储用户组列表

async function getUserGroups() {
  try {
    let resp = await findUserGroup(1, 1000, {}); // 获取所有用户组，假设不超过1000个
    if (resp && resp.records) {
      userGroups.value = resp.records;
    }
  } catch (error) {
    ElMessage({
      message: "获取用户组列表失败",
      type: "error",
    });
    console.error("获取用户组列表失败:", error);
  }
}

function assignGroup(row) {
  assignForm.value.adminId = row.id;
  assignForm.value.userGroupId = '';
  getUserGroups().then(() => {
    showAssignDialog.value = true;
  });
}

async function confirmAssign() {
  if (!assignForm.value.userGroupId) {
    ElMessage({
      message: "请选择用户组",
      type: "warning",
    });
    return;
  }


  try {
    // 假设有一个API函数用于分配用户组
    let resp = await assignAdminToGroup(assignForm.value.adminId, assignForm.value.userGroupId);
    if (resp.code == 200) {
      ElMessage({
        message: "分配成功",
        type: "success",
      });
      showAssignDialog.value = false;
      await search(); // 重新加载数据
    } else {
      ElMessage({
        message: resp.msg || "分配失败",
        type: "error",
      });
    }
  } catch (error) {
    ElMessage({
      message: "分配失败，请稍后重试",
      type: "error",
    });
  }


  ElMessage({
    message: "请在代码中实现具体的分配逻辑",
    type: "info",
  });
  showAssignDialog.value = false;
}

</script>

<style scoped>
.avatar-uploader {
  width: 80px;
  height: 80px;
  border: 1px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader .img {
  width: 80px;
  height: 80px;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center center;
}

.avatar-uploader .icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar-tip {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-top: 5px;
}

.main {
    padding: 0 20px;
}

.data>.pagination {
    margin-top: 10px;
    float: right;
}

.data {
    margin-top: 20px;
}

.search {
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 20px;
    border: 1px solid #ebeef5;
    margin-top: 20px;
}

.mid {
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 20px;
    border: 1px solid #ebeef5;
    margin-top: 20px;
    height: 50px;
}

.search>.button {
    float: right;
}

.el-table td.is-center,
.el-table th.is-center {
    text-align: center;
}

.avatar {
    width: 80px;
    height: 80px;
    border: 1px dashed #ccc;
    border-radius: 4px;
    margin-left: 8px;
    display: flex;
}

.avatar {
    width: 80px;
    height: 80px;
    border: 1px dashed #ccc;
    border-radius: 4px;
    margin-left: 8px;
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
}


.avatar .img {
    width: 80px;
    height: 80px;
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center center;
}
</style>
